//
//  TextInputMaxLength.m
//  etionUI
//
//  Created by wjxfhxy on 14-10-21.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "TextInputMaxLength.h"

#import "XUITextInputSelectedRange.h"

@interface TextInputMaxLength : NSObject

@end

@implementation TextInputMaxLength

+(NSString*)checkTextInput:(id)textInput maxTextWithOriginText:(NSString*)originText maxLength:(NSUInteger)maxLength selectedRange:(NSRange*)selectedRange
{
    BOOL result = FALSE;
    NSString *oriText = originText;
    NSString *lang = [textInput textInputMode].primaryLanguage;
    NSString *newText = nil;
    
    // 简体中文输入，包括简体拼音，健体五笔，简体手写
    if([lang isEqualToString:@"zh-Hans"] || [lang isEqualToString:@"zh_CN"])
    {
        UITextRange *selectedRange = [textInput markedTextRange];
        
        //获取高亮部分
        UITextPosition *position = [textInput positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if(position == nil)
        {
            if(oriText.length > maxLength)
            {
                result = YES;
            }
        }
        else
        {
            result = NO;
        }
    }
    else
    {
        if(oriText.length > maxLength)
        {
            result = YES;
        }
    }
    
    if(result == YES)
    {
        NSRange range = [textInput selectedRange];
        if(range.length <= 0)
        {
            if(range.location >= 1)
                range = NSMakeRange(range.location - (oriText.length - maxLength), oriText.length - maxLength);
            else
                range = NSMakeRange(0, 0);
        }
        newText = [oriText stringByReplacingCharactersInRange:range withString:@""];
        
        range = NSMakeRange(range.location, 0);
        
        *selectedRange = range;
    }
    
    return newText;
}

@end


@implementation UITextField (TextInputMaxLength)

-(NSUInteger)textInputMaxLength
{
    return [self associatedValueForKey:"maxLength"];
}

-(void)setTextInputMaxLength:(NSUInteger)maxLength
{
    [self setAssociatedAssingValue:maxLength withKey:"maxLength"];
    
    if(maxLength > 0)
    {
        [self addTarget:self action:@selector(textFieldTextLengthDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    else
    {
        [self removeTarget:self action:@selector(textFieldTextLengthDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
}

-(void)textFieldTextLengthDidChange:(UITextField*)textFiled
{
    NSRange selectedRange;
    NSString *str = [TextInputMaxLength checkTextInput:self maxTextWithOriginText:self.text maxLength:[self associatedValueForKey:"maxLength"] selectedRange:&selectedRange];
    if(str != nil)
    {
        self.text = str;
        [self setSelectedRange:selectedRange];
    }
}

@end

@implementation XUITextView (TextInputMaxLength)

-(NSUInteger)textInputMaxLength
{
    return [self associatedValueForKey:"maxLength"];
}

-(void)setTextInputMaxLength:(NSUInteger)maxLength
{
    [self setAssociatedAssingValue:maxLength withKey:"maxLength"];
    
    [NSNotificationCenter removeObserver:self name:@"textViewTextLengthDidChange:" object:self];
    
    if(maxLength > 0)
    {
        [NSNotificationCenter addObserver:self dictionarySelector:@{UITextViewTextDidChangeNotification:@"textViewTextLengthDidChange:"} object:self];
    }
}

-(void)textViewTextLengthDidChange:(NSNotification*)noti
{
    if(noti.object != self)
        return;
    
    NSRange selectedRange;
    NSString *str = [TextInputMaxLength checkTextInput:self maxTextWithOriginText:self.text maxLength:[self associatedValueForKey:"maxLength"] selectedRange:&selectedRange];
    if(str != nil)
    {
        self.text = str;
        [self setSelectedRange:selectedRange];
    }
}

//字符长度的限制处理是在输入完字符后进行截取，对于UITextView来说，在粘贴大量字符后，会令控件滚动，
//在滚动动画还没有放完，马上截取处理，就会造成动画播放错误，控件出现空白，此方法通过截取粘贴板的内容，
//解决此问题
-(void)paste:(id)sender
{
    if([self textInputMaxLength] > 0)
    {
        if(self.text.length >= [self textInputMaxLength])
            return;
        
        NSString *str = [UIPasteboard generalPasteboard].string;
        if(str.length > 0 && self.text.length + str.length > [self textInputMaxLength])
        {
            NSUInteger length = [self textInputMaxLength] - self.text.length;
            NSString *tmp = [str substringToIndex:length];
            [UIPasteboard generalPasteboard].string = tmp;
        }
        
        [super paste:sender];
        [UIPasteboard generalPasteboard].string = str;
    }
    else
        [super paste:sender];
}

@end
